<?php

namespace api\modules\common\services;

use common\helpers\CommonHelper;
use common\helpers\EncryptHelper;
use common\models\sys\SysFile;
use services\sys\SysFileService;
use Yii;

class UploadService
{
    /**
     * 文件信息
     * @var
     */
//    protected $fileInfo = [
//        'name' => '',// 原文件名
//        'type' => '',// 文件类型
//        'size' => '',// 大小
//        'error' => 0,// 错误类型
//        'tmp_name' => '',// 文件地址
//    ];

    public static $imageTypeArr = [
        '.jpg', '.jpeg', '.bmp', '.png', '.gif',// 图片
    ];

    public static $videoTypeArr = [
        '.mp4', '.mov', '.mkv',// 视频
    ];

    /**
     * 其他文件类型集合
     * @var array
     */
    public static $otherFileTypeArr = [
//        '.jpg', '.jpeg', '.bmp', '.png', '.gif', '.tga', '.tif',// 图片
//        '.mp4', '.mov', '.mkv',// 视频
        '.pdf', '.xls', '.xlsx', '.docx', '.doc', '.csv', '.ppt', '.pptx', '.epub', '.mobi', '.txt', '.md',// 办公文件
        '.zip', '.rar', '.7z',// 压缩文件
    ];

    /**
     * 文件类型映射集合
     * @var array
     */
    private static $fileTypeMapArr = [
        '.vnd.openxmlformats-officedocument.wordprocessingml.document' => '.docx',
        '.vnd.openxmlformats-officedocument.spreadsheetml.sheet' => '.xlsx',
        '.msword' => '.doc',
        '.msexcel' => '.xls',
    ];

    /**
     * 支持全部文件类型
     * @return array
     */
    public static function getSupportFileTypes(): array
    {
        return array_merge(self::$imageTypeArr, self::$videoTypeArr, self::$otherFileTypeArr);
    }

    /**
     * 初始化参数
     * @param array $params
     * @return array
     */
    protected static function initParams(array $params): array
    {
        $data = [
            'file' => $_FILES['file'] ?? ($params['file'] ?? []),
            'is_file' => isset($_FILES['file']) ? 1 : 0,
            'min' => $params['min'] ?? '',
            'max' => $params['max'] ?? '',
            'file_status' => intval($params['file_status'] ?? 0),
            'site' => isset($params['site']) && $params['site'] ? $params['site'] : 'default',
            'module' => isset($params['module']) && $params['module'] ? $params['module'] : 'default',
        ];
        $data['origin_file'] = [
            'type' => $data['is_file'] ? ($data['file']['type'] ?? '') : ($params['base64_orgin']['type'] ?? ''),
            'name' => $data['is_file'] ? ($data['file']['name'] ?? '') : ($params['base64_orgin']['name'] ?? ''),
            'size' => $data['is_file'] ? ($data['file']['size'] ?? '') : ($params['base64_orgin']['size'] ?? ''),
        ];
        return $data;
    }

    /**
     * 上传文件
     * @param array $params
     * @return array
     * @throws \Exception
     */
    public static function upload(array $params): array
    {
        $params = self::initParams($params);
        try {
            // 验证参数
            $res = self::check($params);
            $fileType = $res['file_type'];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }

        // 生成文件名
        $fileName = date('YmdHis').CommonHelper::getRandomAuthKey();
        $params['fileName'] = $fileNameFormat = $fileName.$fileType;
        // 获取目录
        $fileDir = self::getDir($params['site'], $params['module'], $fileName, $params['file_status']);
        // 文件保存完整路径
        $filePath = $fileDir.$fileNameFormat;
        // 文件转移项目目录
        if ($params['is_file']) {// 文件上传
            if (!copy($params['file']['tmp_name'], $filePath)) {
                return CommonHelper::api(422,'文件拷贝错误');
            }
        } else {// 文件流上传
            file_put_contents($filePath, $params['file']);
            if (filesize($filePath) <= 0) {
                return CommonHelper::api(422,'文件写入错误');
            }
        }
        // 更改文件权限
        chmod($filePath, 0777);
        // 生成小图
        if ($params['min']) {
            $params['minFileName'] = $minFileNameFormat = $fileName.'_min'.$fileType;
            $minFilePath = $fileDir.$minFileNameFormat;

            $sizeInfo = explode(',', $params['min']);
            $width = $sizeInfo[0] ?? 0;
            $heigth = $sizeInfo[1] ?? 0;
//            $type = $sizeInfo[2] ?? 1;

            self::imageEqualResize($filePath, $width, $heigth, $minFilePath);
            chmod($minFilePath, 0777);
        }
        // 生成大图
        if ($params['max']) {
            $params['maxFileName'] = $maxFileNameFormat = $fileName.'_max'.$fileType;
            $maxFilePath = $fileDir.$maxFileNameFormat;

            $sizeInfo = explode(',', $params['max']);
            $width = $sizeInfo[0] ?? 0;
            $heigth = $sizeInfo[1] ?? 0;
//            $type = $sizeInfo[2] ?? 1;

            self::imageEqualResize($filePath, $width, $heigth, $maxFilePath);
            chmod($maxFilePath, 0777);
        }
        if (in_array($fileType, self::$videoTypeArr)) {
            $params['thumbFileName'] = $thumbFileNameFormat = self::getVoiceThumbImageName($fileName);
            $thumbFilePath = $fileDir.$thumbFileNameFormat;
            // 生成视频缩略图
            CommonHelper::createVideoFirstFrameImg($filePath, $thumbFilePath);
        }

        // 保存文件信息
        $sysFile = self::editModel($params);

        // 返回数据
        return [
            'file' => $sysFile->file,
            'status' => $sysFile->status,
            'url' => self::getFileUrl($sysFile->site, $sysFile->module, $sysFile->file),
            'thumb_url' => $sysFile->thumb_file
                ? self::getFileUrl($sysFile->site, $sysFile->module, $sysFile->file, ['thumb' => 1])
                : ($sysFile->min_file
                    ? self::getFileUrl($sysFile->site, $sysFile->module, $sysFile->file, ['min' => 1])
                    : ''),
        ];
    }

    /**
     * 获取视频缩略图名称
     * @param string $voiceFileName
     * @return string
     */
    public static function getVoiceThumbImageName(string $voiceFileName): string
    {
        if (empty($voiceFileName)) {
            return '';
        }
        $fileNameArr = explode('.', $voiceFileName);
        $fileName = $fileNameArr[0] ?? '';
        return $fileName . '_thumb' . self::$imageTypeArr[0];
    }

    /**
     * 获取文件真实格式
     * @param $fileType
     * @return string
     */
    public static function getTrueFileType($fileType): string
    {
        if (in_array($fileType, self::getSupportFileTypes())) {
            return $fileType;
        }
        $fileTypeMapArr = self::$fileTypeMapArr;
        if (isset($fileTypeMapArr[$fileType])) {
            return $fileTypeMapArr[$fileType];
        }
        return '';
    }

    /**
     * 获取文件url
     * @param string $site
     * @param string $module
     * @param string $file
     * @return string
     */
    public static function getFileUrl(string $site, string $module, string $file, array $params = []): string
    {
        $query = [
            'site' => $site,
            'module' => $module,
            'file' => $file,
            'thumb' => $params['thumb'] ?? 0,
            'min' => $params['min'] ?? 0,
        ];
        $queryStr = http_build_query($query);
        return CommonHelper::getHostInfo()."/common/file/index?{$queryStr}";
    }

    /**
     * 获取文件url
     * @param string $site
     * @param string $module
     * @param string $file
     * @return string
     */
    public static function getFileDownloadUrl(string $site, string $module, string $file): string
    {
        $playload = EncryptHelper::encodeFileParams($site, $module, $file);
        return CommonHelper::getHostInfo()."/common/file/download/{$playload}";
    }

    /**
     * 获取缩略图文件名
     * @param string $file
     * @return string
     */
    public static function getMinFile(string $file): string
    {
        list($name, $type) = explode('.', $file);
        return "{$name}_min.{$type}";
    }

    /**
     * 获取真实文件url
     * @param string $site
     * @param string $module
     * @param string $file
     * @return string
     */
    public static function getFileTrueUrl(string $site, string $module, string $file, string $status = SysFile::STATUS_FORMAL, array $params = []): string
    {
        $min = $params['min'] ?? 0;
        $dir = self::getDir($site, $module, $file, $status, 0);
        if ($min) {
            $file = self::getMinFile($file);
        }
        return CommonHelper::getHostInfo()."{$dir}{$file}";
    }

    /**
     * 获取真实文件全路径地址
     * @param string $site
     * @param string $module
     * @param string $file
     * @return string
     */
    public static function getFileTruePath(string $site, string $module, string $file, string $status = SysFile::STATUS_FORMAL): string
    {
        $dir = self::getDir($site, $module, $file, $status);
        return $dir.$file;
    }


    /**
     * 转移正式目录
     * @param array $params
     * @return array
     * @throws \Exception
     */
    public static function move(array $params): array
    {
        $params['site']  = $params['site'] ?? 'default';
        $params['module']  = $params['module'] ?? 'default';
        $params['file']  = $params['file'] ?? '';
        if (empty($params['file'])) {
            throw new \Exception('文件参数不能为空');
        }

        // 批量转移
        $fileArr = is_array($params['file']) ? $params['file'] : explode(',', $params['file']);
        $fileIds = [];
        foreach ($fileArr as $file) {
            // 获取文件信息
            $sysFile = SysFileService::getSysFile($params['site'], $params['module'], $file);
            if (empty($sysFile)) {
                continue;
            }
            // 获取文件目录
            $tmpFileDir = self::getDir($sysFile->site, $sysFile->module, $sysFile->file, $sysFile->status);
            $fileDir = self::getDir($sysFile->site, $sysFile->module, $sysFile->file, SysFile::STATUS_FORMAL);

            // 移动文件至正式目录
            $fileName = $tmpFileDir . $sysFile->file;
            if (is_file($fileName)) {
                rename($fileName, $fileDir . $sysFile->file);
            }
            $minFileName = $tmpFileDir . $sysFile->min_file;
            if (is_file($minFileName)) {
                rename($minFileName, $fileDir . $sysFile->min_file);
            }
            $maxFileName = $tmpFileDir . $sysFile->max_file;
            if (is_file($maxFileName)) {
                rename($maxFileName, $fileDir . $sysFile->max_file);
            }
            $thumbFileName = $tmpFileDir . $sysFile->thumb_file;
            if (is_file($thumbFileName)) {
                rename($thumbFileName, $fileDir . $sysFile->thumb_file);
            }

            // 更新文件信息
            $sysFile->status = SysFile::STATUS_FORMAL;
            $sysFile->saveAndCheckResult();
            $fileIds[] = $sysFile->id;
        }
        return $fileIds;
    }

    /**
     * 移动本地文件
     * @param $params
     * @return SysFile[]
     * @throws \Exception
     */
    public static function moveLocalFile(array $params): array
    {
        $params['site']  = $params['site'] ?? 'default';
        $params['module']  = $params['module'] ?? 'default';
        $params['file']  = $params['file'] ?? '';
        if (empty($params['file'])) {
            throw new \Exception('文件参数不能为空');
        }

        // 批量转移
        $fileArr = is_array($params['file']) ? $params['file'] : explode(',', $params['file']);
        $fileList = [];
        foreach ($fileArr as $file) {
            $fileInfo = pathinfo($file);

            // 生成文件名
            $fileName = date('YmdHis').CommonHelper::getRandomAuthKey();
            $fileName = $fileName.'.'.$fileInfo['extension'];

            // 新增文件
            $sysFile = self::editModel([
                'site' => $params['site'],
                'module' => $params['module'],
                'fileName' => $fileName,
                'origin_file' => [
                    'name' => $fileInfo['basename'],
                    'size' => filesize($file),
                    'type' => $fileInfo['extension'],
                ],
                'file_status' => SysFile::STATUS_FORMAL,
            ]);
            // 获取文件目录
//            $tmpFileDir = self::getDir($sysFile->site, $sysFile->module, $sysFile->file, $sysFile->status);
            $fileDir = self::getDir($sysFile->site, $sysFile->module, $sysFile->file, SysFile::STATUS_FORMAL);

            // 移动文件至正式目录
            $fileName = $file;
            if (is_file($fileName)) {
                rename($fileName, $fileDir . $sysFile->file);
            }

            $fileList[] = $sysFile;
        }
        return $fileList;
    }

    /**
     * 删除图片
     * @param array $params
     * @return bool
     * @throws \Exception
     */
    public static function delete(array $params): void
    {
        $params['site']  = $params['site'] ?? 'default';
        $params['module']  = $params['module'] ?? 'default';
        $params['file']  = $params['file'] ?? '';
        if (empty($params['file'])) {
            throw new \Exception('文件参数不能为空');
        }

        // 批量删除
        $fileArr = is_array($params['file']) ? $params['file'] : explode(',', $params['file']);
        foreach ($fileArr as $file) {
            self::deleteFile($params['site'], $params['module'], $file);
        }
    }

    /**
     * 加载文件
     * @param array $params
     * @return array
     */
    public function loadFile(array $params): array
    {
        $params['site']  = $params['site'] ?? 'default';
        $params['module']  = $params['module'] ?? 'default';
        $params['file']  = $params['file'] ?? '';
        $params['min'] = $params['min'] ?? 0;
        $params['max'] = $params['max'] ?? 0;
        $params['thumb'] = $params['thumb'] ?? 0;
        if (empty($params['file'])) {
            throw new \Exception('文件参数不能为空');
        }
        $sysFile = SysFileService::getSysFile($params['site'], $params['module'], $params['file']);
        if (empty($sysFile)) {
            throw new \Exception('文件不存在');
        }
        if ($params['min']) {
            $file = $sysFile->min_file ?: $sysFile->file;
        } elseif ($params['max']) {
            $file = $sysFile->max_file ?: $sysFile->file;
        } elseif ($params['thumb']) {
            $file = $sysFile->thumb_file ?: $sysFile->file;
        } else {
            $file = $sysFile->file;
        }
        // 获取目录
        $fileDir = self::getDir($sysFile->site, $sysFile->module, $file, $sysFile->status);

        return [
            'relative_file_path' => self::getFileTrueUrl($sysFile->site, $sysFile->module, $file, $sysFile->status),
            'file_path' => $fileDir.$file,
            'file_type' => $sysFile->origin_type,
            'file_name' => $sysFile->origin_name,
            'file_size' => $sysFile->origin_size,
        ];
    }

    /**
     * 删除文件
     * @return bool
     */
    protected static function deleteFile(string $site, string $module, string $file): void
    {
        // 文件信息
        $sysFile = SysFileService::getSysFile($site, $module, $file);
        if ($sysFile) {
            // 获取目录
            $fileDir = self::getDir($sysFile->site, $sysFile->module, $sysFile->file, $sysFile->status);
            @unlink($fileDir.$sysFile->file);
            $sysFile->min_file && @unlink($fileDir.$sysFile->min_file);
            $sysFile->max_file && @unlink($fileDir.$sysFile->max_file);
            $sysFile->thumb_file && @unlink($fileDir.$sysFile->thumb_file);
            // 删除历史数据
            $sysFile->delete();
        }
        return;
    }

    /**
     * 验证参数
     * @return array
     * @throws \Exception
     */
    protected static function check(array $params): array
    {
        if (empty($params['file'])) {
            throw new \Exception('无效上传');
        }
        // 文件上传
        if ($params['is_file'] && $params['file']['error'] > UPLOAD_ERR_OK) {
            switch ($params['file']['error']) {
                case UPLOAD_ERR_INI_SIZE:
                    $msgstr = '图片过大[upload_max_filesize]';
                    break;
                case UPLOAD_ERR_FORM_SIZE:
                    $msgstr = '图片过大[MAX_FILE_SIZE_ERROR]';
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $msgstr = '文件只被部分上传';
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $msgstr = '没有上传任何文件';
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                    $msgstr = '有指定临时目录';
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $msgstr = '文件写入磁盘失败';
                    break;
                case UPLOAD_ERR_EXTENSION:
                    $msgstr = '文件上传因扩展而停止';
                    break;
                default:
                    $msgstr = '未知上传错误';
                    break;
            }
            throw new \Exception($msgstr);
        }
        // base64上传
        if ($params['is_file'] == 0) {
            if (empty($params['origin_file'])) {
                throw new \Exception('base64无效上传');
            }
        }
        // 获取文件类型
        $fileType = substr($params['origin_file']['name'], strrpos($params['origin_file']['name'], '.'));
        $fileType = self::getTrueFileType($fileType);
        if (empty($fileType)) {
            throw new \Exception("不支持{$fileType}文件类型上传");
        }

        return [
            'file_type' => $fileType,
        ];
    }

    /**
     * 保存文件记录
     *
     * @throws \Exception
     */
    protected static function editModel(array $params): SysFile
    {
        // 文件存在先删除
        self::deleteFile($params['site'], $params['module'], $params['fileName']);

        $sysFile = new SysFile();
        $sysFile->site = $params['site'];
        $sysFile->module = $params['module'];
        $sysFile->file = $params['fileName'];
        $sysFile->min_file = $params['minFileName'] ?? '';
        $sysFile->max_file = $params['maxFileName'] ?? '';
        $sysFile->thumb_file = $params['thumbFileName'] ?? '';
        $sysFile->nums = 0;
        $sysFile->origin_name = $params['origin_file']['name'];
        $sysFile->origin_size = $params['origin_file']['size'];
        $sysFile->origin_type = $params['origin_file']['type'];
        $sysFile->status = $params['file_status'];
        $sysFile->saveAndCheckResult();
        return $sysFile;
    }

    /**
     * 获取文件信息
     * @param string $site
     * @param string $module
     * @param $file
     * @return void
     */
    protected function getName(string $site, string $module, $file): array
    {
        // 文件信息
        $sysFile = SysFileService::getSysFile($site, $module, $file);
        $fileDir = self::getDir($sysFile->site, $sysFile->module, $sysFile->file, $sysFile->status);
        return [
            'file_path' => $fileDir.$sysFile->file,
        ];
    }

    /**
     * 获取文件目录【不存在，则创建目录】
     * @param string $site
     * @param string $module
     * @param string $fileName
     * @param int $isFormal  是否正式目录【0临时、1正式】
     * @return string
     */
    public static function getDir(string $site, string $module, string $fileName = '', int $isFormal = SysFile::STATUS_TMP, int $isAllPath = 1): string
    {
        if ($fileName) {
            $date[0] = substr($fileName, 0, 4);
            $date[1] = substr($fileName, 4, 2);
            $date[2] = substr($fileName, 6, 2);
        } else {
            $date = explode('-', date('Y-m-d'));
        }

        // /home/www/new_media/media_backend/web/attachment
        $fileDir = $isAllPath ? Yii::getAlias('@attachment') : '/attachment';
        $fileDir .= $isFormal ? '/' : '/tmp/';
        $dir = $fileDir . $site . '/' . $module . '/' . $date[0] . $date[1] . $date[2] . '/';
        // 是否存在目录
        if (is_dir($dir)) {
            return $dir;
        }
        $isAllPath && mkdir($dir, 0777, true);
        return $dir;
    }

    /**
     * 生成缩略图
     * @param $sourceFile
     * @param $maxWidth
     * @param $maxHeight
     * @param string $targetFile
     * @param int $type
     * @return bool
     */
    protected static function imageResize($sourceFile, $maxWidth, $maxHeight, string $targetFile="", $type=1)
    {
        $targetFile = $targetFile ?: $sourceFile;
        $data = getimagesize($sourceFile);

        switch ($data[2]) {
            case 1:
                $im = imagecreatefromgif($sourceFile);
                break;
            case 2:
                $im = imagecreatefromjpeg($sourceFile);
                break;
            case 3:
                $im = imagecreatefrompng($sourceFile);
                break;
        }

        $srcW = ImageSX($im);
        $srcH = ImageSY($im);
        $toWH = $maxWidth / $maxHeight;// 缩放后
        $srcWH = $srcW / $srcH;


        if ($type == 1) {// 按生成图片比例绽放
            if ($srcW <= $maxWidth && $srcH <= $maxHeight) {
                $ftoW = $srcW;
                $ftoH = $srcH;
            } else {
                if($toWH<=$srcWH) {// 比率
                    $ftoW = $maxWidth;
                    $ftoH = $ftoW * ($srcH / $srcW);
                } else {
                    $ftoH = $maxHeight;
                    $ftoW = $ftoH * ( $srcW / $srcH);
                }
            }
            $src_x = 0;
            $src_y = 0;
        } elseif ($type == 2) {// 按生成图片比例裁剪
            if ($toWH >= $srcWH) {
                $srcW_tmp = $srcW;
                $srcH_tmp = $srcW * ($maxHeight / $maxWidth);
                $src_x = 0;
                $src_y = (int)(($srcH - $srcH_tmp) / 2);
            } else {
                $srcW_tmp = $srcH * ($maxWidth / $maxHeight);
                $srcH_tmp = $srcH;
                $src_x = (int)(($srcW - $srcW_tmp) / 2);
                $src_y = 0;
            }
            //$tmp_img = imagecreatetruecolor($srcW_tmp, $srcH_tmp);
            //imagecopy($tmp_img,$im,0,0,$src_x,$src_y,$srcW_tmp,$srcH_tmp);
            //$im = $tmp_img;
            $srcW = $srcW_tmp;
            $srcH = $srcH_tmp;
            $ftoW=$maxWidth;
            $ftoH=$maxHeight;
        } elseif ($type == 3) {// 定宽
            $ftoW = $maxWidth;
            $ftoH = $maxWidth * ($srcH / $srcW);
            $src_x = 0;
            $src_y = 0;
        }

        if(function_exists("imagecreatetruecolor")) {
            switch ($data[2]) {
                case 1:
                case 3:
                    @$ni = ImageCreateTrueColor((int)$ftoW, (int)$ftoH);
                    $bg =imagecolorallocate($ni, 255, 255, 255);
                    imagefill($ni, 0, 0, $bg);
                    break;
                case 2:
                    @$ni = ImageCreateTrueColor((int)$ftoW, (int)$ftoH);
                    break;
                default:
                    @$ni = ImageCreateTrueColor((int)$ftoW, (int)$ftoH);
                    break;
            }
        }

        if($ni) {
            ImageCopyResampled($ni, $im,0,0, (int)$src_x, (int)$src_y, (int)$ftoW, (int)$ftoH, (int)$srcW, (int)$srcH);
        } else {
            $ni = ImageCreate((int)$ftoW, (int)$ftoH);
            ImageCopyResized($ni, $im,0,0, (int)$src_x, (int)$src_y, (int)$ftoW, (int)$ftoH, (int)$srcW, (int)$srcH);
        }

        if(function_exists('imagejpeg')) {
            ImageJpeg($ni, $targetFile, 75);
        } else {
            ImagePNG($ni, $targetFile, 6);
        }

        ImageDestroy($ni);
        ImageDestroy($im);
        return true;
    }

    /**
     * 生成等比例缩略图
     * @param string $sourceImage
     * @param int $maxWidth
     * @param int $maxHeight
     * @param string $targetFile
     * @return void
     */
    public static function imageEqualResize(string $sourceImage, int $maxWidth, int $maxHeight, string $targetFile): void
    {
        if (is_file($sourceImage) === false) {
            return;
        }
        // 获取原始图像信息
        list($width, $height, $type) = getimagesize($sourceImage);
        // 计算缩放后的尺寸
        if ($width > $height) {
            // 如果原始图像宽度较大，则按照最大宽度进行缩放
            $newWidth = min($maxWidth, $width);
            $newHeight = round(($newWidth / $width) * $height);
        } else {
            // 否则按照最大高度进行缩放
            $newHeight = min($maxHeight, $height);
            $newWidth = round(($newHeight / $height) * $width);
        }
        // 创建新的画布并加载原始图像
        $canvas = imagecreatetruecolor($newWidth, $newHeight);
        // 1=GIF，2=JPG，3=PNG，4=SWF，5=PSD，6=BMP，7=TIFF(intel byte order)，8=TIFF(motorola byte order)，9=JPC，10=JP2，11=PX，12=JB2，13=SWC，14=IFF，15=WBMP，16=XBM。
        $sourceImageObj = null;
        switch ($type) {
            case 1:
                $sourceImageObj = imagecreatefromgif($sourceImage);
                break;
            case 2:
                $sourceImageObj = imagecreatefromjpeg($sourceImage);
                break;
            case 3:
                $sourceImageObj = imagecreatefrompng($sourceImage);
                break;
            case 6:
                $sourceImageObj = imagecreatefrombmp($sourceImage);
                break;
            default:
                break;
        }
        if (empty($sourceImageObj)) {
            return;
        }
        // 将原始图像复制到新的画布上，同时保持其长宽比例不变
        imagecopyresampled($canvas, $sourceImageObj, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        // 保存缩放后的图像文件
        imagejpeg($canvas, $targetFile, 100);
        imagedestroy($canvas);
    }
}
?>